//
//  OauthViewController.swift
//  AAWeibo
//
//  Created by 上官风雨 on 15/11/11.
//  Copyright © 2015年 上官风雨. All rights reserved.
//

import UIKit
import SVProgressHUD

class OauthViewController: UIViewController {
    

    
    var webView : UIWebView?
    
    override func loadView() {
        
        webView = UIWebView()
        view = webView
        webView?.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        loadOauthPage()
    }
    //加载授权网页
    func loadOauthPage(){
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView?.loadRequest(request)
        
    }
    
    func setupUI(){
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
    }
    
    //关闭按钮的点击方法
    func close(){
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    //自动填充
    func fullAccount(){
        
        let jsString = "document.getElementById('userId').value = '15635395802',document.getElementById('passwd').value = 'zxg419'"
        webView?.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
}

extension OauthViewController:UIWebViewDelegate{
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlString = request.URL?.absoluteString else {
            
            return false
        }
        
        if urlString.hasPrefix("https://api.weibo.com/oauth2/authorize"){
            
            return true
        }
        if urlString.hasPrefix("http://weibo.cn/dpool"){
            
            return false
        }
        
        let query = request.URL?.query
        
        let codeStr = "code="
        
        let code = query?.substringFromIndex(codeStr.endIndex)
        
        UserAccountViewModel().loadAccess_token(code!) { (error) -> () in
            
            print("come here")
            
            self.dismissViewControllerAnimated(true, completion: nil)
        }
        
        return false
        
    }
    
}